package com.source.lightfowl.basedata.service.impl;

import com.source.lightfowl.DTO.SlaughterHouseDownloadDTO;
import com.source.lightfowl.DTO.SlaughterHouseUploadDTO;
import com.source.lightfowl.VO.SlaughterHouseVO;
import com.source.lightfowl.basedata.dao.PoultryCategoryDao;
import com.source.lightfowl.basedata.dao.SlaughterHouseDao;
import com.source.lightfowl.basedata.dao.StallsDao;
import com.source.lightfowl.basedata.entity.SlaughterHouse;
import com.source.lightfowl.basedata.service.SlaughterHouseService;
import com.source.lightfowl.constant.ImageCatalogue;
import com.source.lightfowl.handler.MyException;
import com.source.lightfowl.person.dao.PersonDao;
import com.source.lightfowl.person.entity.Person;
import com.source.lightfowl.person.entity.UsersExtends;
import com.source.lightfowl.utils.ImageUtil;
import com.source.lightfowl.utils.StringTOArrayList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author: cxy
 * @Description: 屠宰市场
 */
@Service
public class SlaughterHouseServiceImpl implements SlaughterHouseService {

    @Autowired
    private SlaughterHouseDao slaughterHouseDao;
    @Autowired
    private StallsDao stallsDao;
    @Autowired
    private PoultryCategoryDao poultryCategoryDao;
    @Autowired
    private PersonDao personDao;

    //查找全部
    @Override
    public List<SlaughterHouseVO> findAll(int state) {
        List<SlaughterHouse> all = slaughterHouseDao.findByState(state);
        return changeToVOList(all);
    }

    //分页查找
    @Override
    public Page<SlaughterHouse> findAllPage(int page, int pageNum) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageNum);
        return slaughterHouseDao.findByState(1, pageRequest);
    }

    //保存一条记录
    @Override
    public void save(SlaughterHouse sh) {
        if (sh.getCreateDate() == null) {
            sh.setCreateDate(new Date());
        }
        slaughterHouseDao.save(sh);
    }

    @Override
    public void save(SlaughterHouse sh, MultipartFile file, HttpServletRequest request) {
        if (sh.getCreateDate() == null || sh.getCreateDate().equals("")) {
            sh.setCreateDate(new Date());
        }
        if (file != null) {
            String s = null;
            try {
                s = ImageUtil.saveImage(file, ImageCatalogue.SlaughterHouse_Catalogue);
            } catch (Exception e) {
                System.out.println("图片保存异常");
                System.out.println(e.getMessage());
            }
            //删除原来的图片
            String mag = sh.getMarketPictures();
            try {
                ImageUtil.delete(mag, ImageCatalogue.SlaughterHouse_Catalogue);
            } catch (Exception e) {
            }
            sh.setMarketPictures(s);
        }
        slaughterHouseDao.save(sh);
    }

    //根据id删除
    @Override
    public void deleteById(Integer id) {
        SlaughterHouse slaughterHouse = slaughterHouseDao.findById(id).get();
        slaughterHouse.setState(3);
        slaughterHouseDao.save(slaughterHouse);
        slaughterHouseDao.save(slaughterHouse);
    }

    //批量删除
    @Override
    public void deleteBatch(int state, String ids) {
        ArrayList<Integer> list = StringTOArrayList.toArrayList(ids);
        ArrayList<String> slist = StringTOArrayList.toStringArrayList(ids);
        stallsDao.deleteBySlaughterHouseId(slist);
        poultryCategoryDao.deleteBySlaughterHouseId(slist);
        for (Integer id :
                list) {
            deletePic(id);
        }
        slaughterHouseDao.changeBatch(state, list);
    }

    @Override
    public void changeBatch(int state, String ids) {
        ArrayList<Integer> list = StringTOArrayList.toArrayList(ids);
        slaughterHouseDao.changeBatch(state, list);
    }

    //根据id查找
    @Override
    public Optional<SlaughterHouse> findById(Integer id) {
        Optional<SlaughterHouse> house = slaughterHouseDao.findById(id);
        return house;
    }

    @Override
    public SlaughterHouseVO findByIdVO(Integer id) {
        SlaughterHouse s = slaughterHouseDao.findByIdAndStateNot(id, 0);
        return changeToVO(s);
    }

    @Override
    public String findIdByUser(String id) {
        return slaughterHouseDao.findIdByUser(id);
    }

    //根据名字模糊匹配
    @Override
    public List<SlaughterHouseVO> getByLikeName(String name) {
        List<SlaughterHouse> res = slaughterHouseDao.getLikeName(1, name);
        return changeToVOList(res);
    }

    @Override
    public List<String> findByProvince(String province) {
        return slaughterHouseDao.findCity(1, province);
    }

    @Override
    public List<String> findByCity(String province, String city) {
        return slaughterHouseDao.findDistrict(1, province, city);
    }

    @Override
    public List<SlaughterHouse> findByDistrict(String province, String city, String district) {
        return slaughterHouseDao.findSlaughterHouse(1, province, city, district);
    }

    @Override
    public Page<SlaughterHouseVO> findAllPageVO(int state, int page, int pageNum) {
        Page<SlaughterHouse> slaughterHousePage = slaughterHouseDao.findByState(state, PageRequest.of(page - 1, pageNum));
        List<SlaughterHouseVO> list = new LinkedList<>();
        for (SlaughterHouse s :
                slaughterHousePage.getContent()) {
            SlaughterHouseVO vo = new SlaughterHouseVO();
            BeanUtils.copyProperties(s, vo);
            list.add(vo);
        }
        return new PageImpl<SlaughterHouseVO>(list, PageRequest.of(page - 1, pageNum), slaughterHousePage.getTotalElements());
    }

    @Override
    public List<Object> findAllDTO() {
        List<SlaughterHouse> slaughterHouseList = slaughterHouseDao.findByState(1);
        List<Object> list = new ArrayList<>();
        for (SlaughterHouse s :
                slaughterHouseList) {
            SlaughterHouseDownloadDTO dto = new SlaughterHouseDownloadDTO();
            BeanUtils.copyProperties(s, dto);
            if (s.getContacts() != null && !s.getContacts().equals("")) {
                Person contacts = personDao.findVO(s.getContacts());
                if (contacts != null) {
                    dto.setContactsName(contacts.getName());
                    dto.setMobile(contacts.getMobile());
                    dto.setPhone(contacts.getPhone());
                }
            }
            String address = "";
            if (s.getProvince() != null)
                address += s.getProvince();
            if (s.getCity() != null)
                address += s.getCity();
            if (s.getDistrict() != null)
                address += s.getDistrict();
            if (s.getAddress() != null)
                address += s.getAddress();
            dto.setAddr(address);
            list.add(dto);
        }
        return list;
    }

    @Override
    public void save(List<Object> list, HttpServletRequest request) {
        String creatBy = null;
        try {
            UsersExtends usersExtends = (UsersExtends) request.getAttribute("usersExtends");
            creatBy = usersExtends.getUser().getLoginName();
        } catch (Exception e) {
            throw new MyException(500, "未找到用户登录信息");
        }
        List<SlaughterHouse> slaughterHouseList = new ArrayList<>();
        for (Object object :
                list) {
            SlaughterHouse slaughterHouse = new SlaughterHouse();
            SlaughterHouseUploadDTO dto = (SlaughterHouseUploadDTO) object;
            BeanUtils.copyProperties(dto, slaughterHouse);
            if (dto.getUserName() != null && !dto.getUserName().equals("")) {
                Person user = personDao.findByName(dto.getUserName());
                if (user == null) {
                    throw new MyException(500, "负责人姓名有误，未找到负责人");
                }
                slaughterHouse.setUserId(user.getId());
                System.out.println(user.getId());
            }
            if (dto.getContactsName() != null && !dto.getContactsName().equals("")) {
                Person user = personDao.findByName(dto.getContactsName());
                if (user == null) {
                    throw new MyException(500, "联系人姓名有误，未找到联系人");
                }
                slaughterHouse.setContacts(user.getId());
            }
            slaughterHouse.setCreateDate(new Date());
            slaughterHouse.setState(1);
            slaughterHouse.setCreatBy(creatBy);
            slaughterHouseList.add(slaughterHouse);
        }
        slaughterHouseDao.saveAll(slaughterHouseList);
    }

    //把List<SlaughterHouse>改成List<SlaughterHouseVO>
    private List<SlaughterHouseVO> changeToVOList(List<SlaughterHouse> slaughterHouseList) {
        List<SlaughterHouseVO> list = new ArrayList<>();
        for (SlaughterHouse s :
                slaughterHouseList) {
            list.add(changeToVO(s));
        }
        return list;
    }

    //把SlaughterHouse改成SlaughterHouseVO
    private SlaughterHouseVO changeToVO(SlaughterHouse s) {
        SlaughterHouseVO vo = new SlaughterHouseVO();
        BeanUtils.copyProperties(s, vo);
        if (s.getUserId() != null && !s.getUserId().equals("")) {
            Person user = personDao.findVO(s.getUserId());
            if (user != null) {
                vo.setUserName(user.getName());
                vo.setUserQq(user.getQq());
                vo.setUserWechat(user.getWechat());
                vo.setUserWechatCode(user.getWechatCode());
            }
        }
        if (s.getContacts() != null && !s.getContacts().equals("")) {
            Person contacts = personDao.findVO(s.getContacts());
            if (contacts != null) {
                vo.setContactsName(contacts.getName());
                vo.setMobile(contacts.getMobile());
                vo.setPhone(contacts.getPhone());
            }
        }
        return vo;
    }

    private void deletePic(Integer id) {
        SlaughterHouse slaughterHouse = slaughterHouseDao.findById(id).get();
        if (slaughterHouse != null) {
            String mag = slaughterHouse.getMarketPictures();
            if (mag != null && !mag.equals(""))
                ImageUtil.delete(mag, ImageCatalogue.SlaughterHouse_Catalogue);
        }
    }
}
